package com.github.jameszbl.toolkits

import android.content.Intent
import android.graphics.Point
import android.os.Bundle
import android.view.SurfaceHolder
import android.view.SurfaceHolder.Callback
import android.view.SurfaceView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.common.api.CommonStatusCodes
import com.google.android.gms.vision.CameraSource
import com.google.android.gms.vision.Detector
import com.google.android.gms.vision.Detector.Processor
import com.google.android.gms.vision.barcode.Barcode
import com.google.android.gms.vision.barcode.BarcodeDetector

class QrActivity : AppCompatActivity() {

    private var mWidth: Int = -1
    private var mHeight: Int = -1
    private lateinit var preview: SurfaceView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_qr)
        preview = findViewById(R.id.preview)
        val display = windowManager.defaultDisplay
        val size = Point()
        display.getSize(size)
        val width = size.x
        mHeight = size.y
        mWidth = ((9 / 16.0) * mHeight).toInt()
        val layoutParams = preview.layoutParams as LinearLayout.LayoutParams
        layoutParams.width = mWidth
        layoutParams.height = mHeight
        layoutParams.leftMargin = -(0.5 * (mWidth - width)).toInt()
        createCameraSource()
    }

    private fun createCameraSource() {
        val detector = BarcodeDetector.Builder(applicationContext)
            .setBarcodeFormats(Barcode.ALL_FORMATS).build()
        val cameraSource = CameraSource.Builder(this, detector)
            .setAutoFocusEnabled(true)
            .build()
        preview.holder?.addCallback(object : Callback {
            override fun surfaceChanged(
                holder: SurfaceHolder?,
                format: Int,
                width: Int,
                height: Int
            ) {
                try {
                    cameraSource.start(preview.holder)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun surfaceDestroyed(holder: SurfaceHolder?) {
                cameraSource.stop()
            }

            override fun surfaceCreated(holder: SurfaceHolder?) {
            }
        })
        detector.setProcessor(object : Processor<Barcode> {
            override fun release() {

            }

            override fun receiveDetections(detections: Detector.Detections<Barcode>?) {
                val detectedItems = detections?.detectedItems
                if (0 < detectedItems?.size()!!) {
                    val intent = Intent()
                    intent.putExtra("barcode", detectedItems.valueAt(0))
                    setResult(CommonStatusCodes.SUCCESS, intent)
                    finish()
                }
            }
        })
    }
}
